package com.example.design.b.composite.demo;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 树枝构件
 * 购物袋
 */
public class Bag implements Component {
    /**
     * 购物袋标识
     */
    private final String name;

    public Bag(String name) {
        this.name = name;
    }

    /**
     * 子容器列表(用于表示购物车里的购物袋)
     */
    private final List<Component> items = new ArrayList<>();

    /**
     * 袋子或其他容器装东西
     *
     * @param component
     */
    @Override
    public void add(Component component) {
        if (component != null) {
            items.add(component);
        }
    }

    /**
     * 移除一样东西
     *
     * @param component
     */
    @Override
    public void remove(Component component) {
        if (component != null) {
            items.remove(component);
        }
    }

    /**
     * 计算当前容器中物品价格
     *
     * @return
     */
    @Override
    public double cal() {
        if (items.size() > 0) {
            double result = 0D;
            for (Component item : items) {
                result += item.cal();
            }
            return result;
        }
        return 0;
    }

    @Override
    public void show() {
        if (items.size() > 0) {
            for (Component item : items) {
                item.show();
            }
            return;
        }
        System.out.println("袋子里是空的");
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Bag bag = (Bag) o;
        return name.equals(bag.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(name);
    }
}
